﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

using SRM.Core.Extension;
using SRM.Core.Models;
using SRM.Core.Utility;

using System;
using System.Linq;

namespace SRM.DataAccess.Seed
{
    public static class DataInitializer
    {
        public static IApplicationBuilder UseDataInitializer(this IApplicationBuilder builder)
        {
            using (var scope = builder.ApplicationServices.CreateScope())
            {
                var dbContext =
                       scope.ServiceProvider.GetService<AppDbContext>();
                var userManager =
                    scope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
                var roleManager =
                    scope.ServiceProvider.GetService<RoleManager<IdentityRole>>();

                #region 种子数据

                if (dbContext.Users.Count() < 2)
                    UserRoleInit(dbContext, userManager);

                if (dbContext.PurchaseOrders.Any() == false)
                    PurchaseOrderInit(dbContext);

                if (dbContext.ReturnOrders.Any() == false)
                    ReturnOrderInit(dbContext);

                if (dbContext.DeliverOrders.Any() == false)
                    DeliverOrderInit(dbContext);

                return builder;
                #endregion
            }
        }

        private static ApplicationUser user;//创建产品要使用用户Id

        private static void UserRoleInit(AppDbContext dbContext, UserManager<ApplicationUser> userManager)
        {
            ApplicationUser applicationUser = new ApplicationUser
            {
                UserName = "dev",
                SupplierNo = "",
                SupplierName = "",
                RoleName = Consts.Admin
            };
            IdentityResult identityResult = userManager.CreateAsync(applicationUser, "123456").Result;
            dbContext.SaveChanges();

            var role =
                new IdentityRole { Name = Consts.Admin, NormalizedName = Consts.Admin.ToUpper() };
            dbContext.Roles.Add(role);
            dbContext.SaveChanges();
            if (identityResult.Succeeded)
            {
                var key = new IdentityUserRole<string> { UserId = applicationUser.Id, RoleId = role.Id };
                dbContext.UserRoles.Add(key);
                dbContext.SaveChanges();
            }
            else
            {
                string errorString = "";
                foreach (var error in identityResult.Errors)
                {
                    errorString += $"{error.Description}\r\n";
                }
                new Exception(errorString);
            }

            user = new ApplicationUser
            {
                UserName = "nick",
                SupplierNo = SecurityHelper.GeneratePassword(5).ToUpper(),
                SupplierName = "马诗琪",
                RoleName = Consts.Supplier
            };
            IdentityResult identityResult2 = userManager.CreateAsync(user, "123456").Result;
            dbContext.SaveChanges();

            #region 创建用户
            ApplicationUser user2 = new ApplicationUser
            {
                UserName = "Kate",
                SupplierNo = SecurityHelper.GeneratePassword(5).ToUpper(),
                SupplierName = "凯特",
                RoleName = Consts.Supplier
            };
            var r2 = userManager.CreateAsync(user2, "123456").Result;
            dbContext.SaveChanges();

            ApplicationUser user3 = new ApplicationUser
            {
                UserName = "Susan",
                SupplierNo = SecurityHelper.GeneratePassword(5).ToUpper(),
                SupplierName = "苏珊",
                RoleName = Consts.Supplier
            };
            var r3 = userManager.CreateAsync(user3, "123456").Result;
            dbContext.SaveChanges();
            #endregion

            var role2 =
                new IdentityRole { Name = Consts.Supplier, NormalizedName = Consts.Supplier.ToUpper() };
            dbContext.Roles.Add(role2);
            dbContext.SaveChanges();

            if (identityResult2.Succeeded)
            {
                var key1 = new IdentityUserRole<string> { UserId = user.Id, RoleId = role2.Id };
                dbContext.UserRoles.Add(key1);

                var key2 = new IdentityUserRole<string> { UserId = user2.Id, RoleId = role2.Id };
                dbContext.UserRoles.Add(key2);

                var key3 = new IdentityUserRole<string> { UserId = user3.Id, RoleId = role2.Id };
                dbContext.UserRoles.Add(key3);

                dbContext.SaveChanges();
            }
            else
            {
                string errorString = "";
                foreach (var error in identityResult.Errors)
                {
                    errorString += $"{error.Description}\r\n";
                }
                new Exception(errorString);
            }
        }

        private static void PurchaseOrderInit(AppDbContext dbContext)
        {
            for (int i = 0; i < 100; i++)
            {
                int j = i + 1;
                PurchaseOrder purchase = new PurchaseOrder();
                purchase.ItemCode = "ZL00" + j;
                purchase.ItemName = $"品牌{j}号";
                purchase.Remark = $"品牌{j}号";
                purchase.ReviewBy = "林梦泽";
                purchase.ReviewDate = DateTime.Now;
                purchase.CreateBy = "林梦泽";
                purchase.CreateDate = DateTime.Now;
                purchase.PurchaseOrderNo = "P" + SecurityHelper.GeneratePassword(6).ToUpper();
                if (i <= 80)
                    purchase.ReviewState = PurchaseOrderStateEnum.转回货计划;
                else
                    purchase.ReviewState = PurchaseOrderStateEnum.未审核;
                purchase.PurchaseCount = 30;

                if (i % 5 == 0)
                {
                    purchase.PurchaseOrderType = PurchaseOrderTypeEnum.网络产品;
                }
                else if (i % 6 == 0)
                {
                    purchase.PurchaseOrderType = PurchaseOrderTypeEnum.办公设备;
                }
                else if (i % 7 == 0)
                {
                    purchase.PurchaseOrderType = PurchaseOrderTypeEnum.外设产品;
                }
                else if (i % 9 == 0)
                {
                    purchase.PurchaseOrderType = PurchaseOrderTypeEnum.游戏设备;
                }
                else
                {
                    purchase.PurchaseOrderType = PurchaseOrderTypeEnum.电脑整机;
                }

                purchase.SupplierId = user.Id;
                purchase.SupplierNo = "S" + SecurityHelper.GeneratePassword(4).ToUpper();
                purchase.SupplierName = "张" + SecurityHelper.GeneratePassword(2).ToUpper();
                purchase.Address = "佛山";
                purchase.Checkbox = false;

                dbContext.PurchaseOrders.Add(purchase);
                dbContext.SaveChanges();

                for (int k = 0; k < 3; k++)
                {
                    PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail()
                    {
                        PurchaseOrderId = purchase.Id,
                        Code = $"L00{k + 1}",
                        Name = "华硕",
                        Spec = "15*40*30",
                        Color = "金属白",
                        Material = $"PPEC{k + 1}",
                        Price = 6599.99m,
                        Currency = "人民币",
                        NetFinallyPriceFC = 6599.99m * 0.4m,
                        TaxRate = 0.4m,
                        Remark = "笔记本电脑"
                    };
                    dbContext.PurchaseOrderDtl.Add(purchaseOrderDetail);
                    dbContext.SaveChanges();
                }
            }
        }

        private static void ReturnOrderInit(AppDbContext dbContext)
        {
            for (int l = 1; l < 101; l++)
            {
                ReturnOrder returnOrder = new ReturnOrder();
                returnOrder.ItemCode = "ZLR00" + l;
                returnOrder.ItemName = $"品牌{l}号";
                returnOrder.Remark = $"品牌{l}号";
                returnOrder.ReviewBy = "袁世琪";
                returnOrder.ReviewDate = DateTime.Now;
                returnOrder.CreateBy = "袁世琪";
                returnOrder.CreateDate = DateTime.Now;
                returnOrder.ReturnOrderNo = "R" + SecurityHelper.GeneratePassword(6).ToUpper();
                if (l <= 60)
                    returnOrder.ReviewState = ReturnOrderStateEnum.已复审;
                else
                    returnOrder.ReviewState = ReturnOrderStateEnum.未审核;
                returnOrder.ReturnOrderCount = 20;

                if (l % 5 == 0)
                {
                    returnOrder.OrderType = "网络产品";
                }
                else if (l % 6 == 0)
                {
                    returnOrder.OrderType = "办公设备";
                }
                else if (l % 7 == 0)
                {
                    returnOrder.OrderType = "外设产品";
                }
                else if (l % 9 == 0)
                {
                    returnOrder.OrderType = "游戏设备";
                }
                else
                {
                    returnOrder.OrderType = "电脑整机";
                }
                returnOrder.SupplierId = user.Id;
                var puchras = dbContext.PurchaseOrders.FirstOrDefault(p => p.Id == l);
                returnOrder.PurchaseOrders = puchras == null ? dbContext.PurchaseOrders.FirstOrDefault() : puchras;
                returnOrder.PurchaseOrderId = l;

                dbContext.ReturnOrders.Add(returnOrder);
                dbContext.SaveChanges();

                for (int m = 1; m < 4; m++)
                {
                    ReturnOrderDetail detail = new ReturnOrderDetail()
                    {
                        ReturnOrderId = returnOrder.Id,
                        Code = $"R00{m}",
                        Name = "华硕",
                        Spec = "15*40*30",
                        Color = "金属白",
                        Material = $"PPEC{m}",
                        Price = 6599.99m,
                        Currency = "人民币",
                        NetFinallyPriceFC = 6599.99m * 0.4m,
                        TaxRate = 0.4m,
                        Remark = "笔记本电脑"
                    };
                    dbContext.ReturnOrderDtl.Add(detail);
                    dbContext.SaveChanges();
                }
            }
        }

        private static void DeliverOrderInit(AppDbContext dbContext)
        {
            for (int n = 0; n < 101; n++)
            {
                DeliverOrder deliverOrders = new DeliverOrder();
                deliverOrders.ItemCode = $"ZLD00{n}";
                deliverOrders.ItemName = $"品牌{n}号";
                deliverOrders.Remark = $"品牌{n}号";
                deliverOrders.ReviewBy = "猪刚鬣";
                deliverOrders.ReviewDate = DateTime.Now;
                deliverOrders.CreateBy = "猪刚鬣";
                deliverOrders.CreateDate = DateTime.Now;
                deliverOrders.DeliverOrderNo = "D" + SecurityHelper.GeneratePassword(6).ToUpper();
                deliverOrders.OrderType = "电脑整机";
                if (n % 5 == 0)
                {
                    deliverOrders.OrderType = "网络产品";
                }
                else if (n % 6 == 0)
                {
                    deliverOrders.OrderType = "办公设备";
                }
                else if (n % 7 == 0)
                {
                    deliverOrders.OrderType = "外设产品";
                }
                else if (n % 9 == 0)
                {
                    deliverOrders.OrderType = "游戏设备";
                }
                else
                {
                    deliverOrders.OrderType = "电脑整机";
                }
                deliverOrders.ReviewState = DeliverOrderStateEnum.未审核;
                deliverOrders.SupplierId = user.Id;
                var purchaseOrder = dbContext.PurchaseOrders.FirstOrDefault(p => p.Id == (n + 1));
                if (purchaseOrder == null)
                {
                    var data = dbContext.PurchaseOrders.First();
                    deliverOrders.PurchaseOrderId = data.Id;
                    deliverOrders.PurchaseOrder = data;
                }
                else
                {
                    deliverOrders.PurchaseOrderId = purchaseOrder.Id;
                    deliverOrders.PurchaseOrder = purchaseOrder;
                }
                var returnOrder = dbContext.ReturnOrders.FirstOrDefault(r => r.Id == (n + 1));
                if (returnOrder == null)
                {
                    var data = dbContext.ReturnOrders.First();
                    deliverOrders.ReturnOrderId = data.Id;
                    deliverOrders.ReturnOrder = data;
                }
                else
                {
                    deliverOrders.ReturnOrderId = returnOrder.Id;
                    deliverOrders.ReturnOrder = returnOrder;
                }

                dbContext.DeliverOrders.Add(deliverOrders);
                dbContext.SaveChanges();

                for (int o = 1; o < 4; o++)
                {
                    DeliverOrderDetail detail = new DeliverOrderDetail()
                    {
                        DeliverOrderId = deliverOrders.Id,
                        Code = $"D00{o}",
                        Name = "华硕",
                        Spec = "15*40*30",
                        Color = "金属白",
                        Material = $"PPEC{o}",
                        Price = 6599.99m,
                        Currency = "人民币",
                        NetFinallyPriceFC = 6599.99m * 0.4m,
                        TaxRate = 0.4m,
                        Remark = "笔记本电脑",
                        Receiving = "刘睿",
                        Phone = "16522336589",
                        Address = "佛山禅城区",
                        IsLiquidation = true,
                        LiquidationType = o % 2 == 0 ? LiquidationTypeEnum.现金支付 : LiquidationTypeEnum.电子账户
                    };
                    dbContext.DeliverOrderDtl.Add(detail);
                    dbContext.SaveChanges();
                }
            }
        }

    }
}


